<template>
  <div>
    <div class="add-container">
      <div class="add-title">
        <h1>我的资料</h1>
      </div>
<!--      用户头像-->
      <Card style="height: 283px;">
        <p slot="title">
          <Icon type="ios-pricetags-outline"></Icon>
          用户头像
        </p>
        <Upload
          ref="upload_pic"
          :show-upload-list="false"
          :format="['jpg', 'jpeg', 'png']"
          :max-size="2048"
          type="drag"
          name="file"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-error="updateError"
          :action='qiniuAction'
          :data="qiniuData">
          <div style="width:58px;height:58px;line-height:58px;">
            <Icon type="camera" size="20"></Icon>
          </div>
        </Upload>
        <br />
         <img :src="formData.avatar" id="test" alt="返回的图片" width="100" height="100" />
      </Card>
      <br />
      <div class="add-box">
        <Form
          ref="form"
          :model="formData"
          label-position="left"
          :label-width="100"
          :rules="ruleInline"
        >
          <FormItem label="用户昵称" prop="nickName" class="itemRequired">
            <i-input v-model="formData.nickName" size="large"></i-input>
          </FormItem>
          <FormItem label="用户名称" prop="userName" class="itemRequired">
            <i-input v-model="formData.userName" size="large"></i-input>
          </FormItem>
          <FormItem label="用户邮箱" prop="email" class="itemRequired">
            <i-input v-model="formData.email" size="large"></i-input>
          </FormItem>
          <FormItem label="手机号码" prop="phoneNumber" class="itemRequired">
            <i-input v-model="formData.phoneNumber" size="large"></i-input>
          </FormItem>
          <FormItem label="用户性别" class="itemRequired">
            <Select v-model="formData.sex" style="width:100px">
              <Option v-for="item in sexOption" :value="item.value" :key="item.key">{{ item.value }}</Option>
            </Select>
          </FormItem>
          <FormItem label="用户密码" prop="password" hidden="true" class="itemRequired">
            <i-input v-model="formData.password" size="large"></i-input>
          </FormItem>
          <FormItem label="会员等级" prop="level" hidden="true" class="itemRequired">
            <i-input v-model="formData.level" size="large"></i-input>
          </FormItem>
          <FormItem label="用户积分" prop="integral" hidden="true" class="itemRequired">
            <i-input v-model="formData.integral" size="large"></i-input>
          </FormItem>
        </Form>
      </div>
      <div class="add-submit">
        <template>
          <i-button type="primary" @click="editUser">保存修改</i-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {mapActions, mapMutations} from "vuex";

const sexOption = [
  {key: 1, value: '男'},
  {key: 2, value: '女'}
]

// 用户昵称
const nickNameValidate = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,6}$/
  if (value === undefined || value === '') {
    callback(new Error('昵称不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入2-6个汉字'))
  } else {
    callback()
  }
}
// 用户姓名
const userNameValidate = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s\-]{2,6}$/
  if (value === undefined || value === '') {
    callback(new Error('用户姓名不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入2-6个汉字！'))
  } else {
    callback()
  }
}
// 电话号码
const tellValidate = (rule, value, callback) => {
  const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
  if (value === undefined || value === '') {
    callback(new Error('电话不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的电话号码'))
  } else {
    callback()
  }
}
// 邮箱
const emailValidate = (rule, value, callback) => {
  const reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
  if(value === undefined || value === '') {
    callback(new Error('邮箱不能为空'))
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的邮箱'))
  } else {
    callback()
  }
}

export default {
  name: "UserInfo",
  // 注入依赖
  // inject: ["reload"],
  data() {
    return {
      qiniuAction:"https://upload-z2.qiniup.com",//七牛云上传地址-华南
      qiniuData: {
        token: "",
        key: ''
      },
      qiniu_OutChain: 'http://qwq973aqg.hn-bkt.clouddn.com',//七牛云图片外链地址
      sexOption,
      formData: {
        nickName: "",
        userName: "",
        email: "",
        phoneNumber: "",
        sex: "男",
        avatar: "",//传到后台的pic地址
        createTime: "",
        updateTime: "",
        id: "",
        password: "",
        level: "",
        integral: ""
      },
      ruleInline: {
        userName: [{validator:userNameValidate, trigger: "blur"}],
        nickName: [{validator:nickNameValidate, trigger: "blur"}],
        email: [{validator:emailValidate, trigger: "blur"}],
        phoneNumber: [{validator:tellValidate, trigger: "blur"}]
      }
    };
  },
  created: function() {
    this.getInfo()
    this.getToken();
  },
  methods: {
    // 七牛云上传头像
    // 获得token
    getToken() {
      const _this = this
      this.$http.get('/qiniu/token')
        .then(resp => {
          _this.qiniuData.token = resp.data.data.token;
        });
    },
    // 上传图片之前进行处理
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$Message.error("上传头像图片大小不能超过2MB!")
        return false
      }
      this.qiniuData.key = `upload_pic_${file.name}`;
    },
    // 上传成功
    handleSuccess(res) {
      this.formData.avatar = `${this.qiniu_OutChain}/${res.key}`
    },
    // 上传失败
    updateError(err) {
      this.$Message.error("上传失败,请重试!")
    },
    // 修改用户信息
    editUser() {
      const _this = this;
      const user = this.formData;
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$http.put("/user/editUser", user)
            .then(resp => {
              _this.$Message.success("修改成功");
              sessionStorage.setItem('loginInfo',JSON.stringify(user))
              this.getInfo()
            }).cache(err => {
              _this.$Message.error("修改失败")
            })
        }
      })
    },
    // 获得用户信息
    getInfo() {
      let user = sessionStorage.getItem('loginInfo')
      let userinfo = (JSON.parse(user))
      this.formData = userinfo;
    }
  }
};
</script>

<style scoped>
  .add-container {
    margin: 15px auto;
    width: 60%;
    min-width: 600px;
  }

  .add-title {
    margin-bottom: 15px;
    text-align: center;
  }

  .add-submit {
    display: flex;
    justify-content: center;
  }

  .itemRequired>>>label.ivu-form-item-label::before {
    content: '* ';
    color: #F56C6C;
    margin-right: 2px;
  }
</style>
